<template>
  <Layout>
    <div class="content-header">
      <h2>监控配置</h2>
    </div>
    <div class="content-body">
      <el-card class="config-card">
        <template #header>
          <div class="card-header">
            <span>监控配置</span>
            <div>
              <el-button type="primary" @click="openAddDialog" id="add-server-btn">新增服务器</el-button>
              <el-button type="success" @click="openImportDialog">批量导入</el-button>
            </div>
          </div>
        </template>
      
        <el-table :data="paginatedServerList" style="width: 100%" border>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="服务器名称" />
          <el-table-column prop="ip" label="IP地址" />
          <el-table-column prop="os" label="操作系统" />
          <el-table-column prop="owner" label="负责人" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
                {{ scope.row.status === 'online' ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="editServer(scope.row)">编辑</el-button>
              <el-button size="small" @click="configServer(scope.row)">配置</el-button>
              <el-button size="small" @click="updateServerActivate(scope.row)">{{ scope.row.is_activate? '禁用' : '启用'}}</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <Pagination
          :current-page="currentPage"
          :total-pages="totalPages"
          :page-size="pageSize"
          :total-items="totalItems"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </el-card>
      
      <!-- 新增/编辑服务器对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
        <el-form :model="currentServer" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="服务器名称" prop="name">
            <el-input v-model="currentServer.name" placeholder="请输入服务器名称" />
          </el-form-item>
          <el-form-item label="IP地址" prop="ip">
            <el-input v-model="currentServer.ip" placeholder="请输入服务器IP地址" />
          </el-form-item>
          <el-form-item label="操作系统" prop="os">
            <el-input v-model="currentServer.os" placeholder="请输入操作系统" />
          </el-form-item>
          <el-form-item label="负责人" prop="owner">
            <el-input v-model="currentServer.owner" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <el-input v-model.number="currentServer.port" placeholder="请输入端口号" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="currentServer.description" type="textarea" placeholder="请输入服务器描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveServer">保存</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 服务器监控配置对话框 -->
      <el-dialog v-model="configDialogVisible" title="服务器监控配置" width="600px">
        <el-form :model="agentConfig" label-width="150px">
          <el-form-item label="监控间隔(秒)">
            <el-input-number v-model="agentConfig.interval" :min="1" :max="3600" />
          </el-form-item>
          
          <el-form-item label="收集系统信息">
            <el-switch v-model="agentConfig.collect_system_info" />
          </el-form-item>
          
          <el-form-item label="收集CPU信息">
            <el-switch v-model="agentConfig.collect_cpu_info" />
          </el-form-item>
          
          <el-form-item label="收集内存信息">
            <el-switch v-model="agentConfig.collect_memory_info" />
          </el-form-item>
          
          <el-form-item label="收集磁盘信息">
            <el-switch v-model="agentConfig.collect_disk_info" />
          </el-form-item>
          
          <el-form-item label="收集网络信息">
            <el-switch v-model="agentConfig.collect_network_info" />
          </el-form-item>
          
          <el-form-item label="收集进程信息">
            <el-switch v-model="agentConfig.collect_process_info" />
          </el-form-item>
          
          <el-form-item label="监控进程名称列表" v-if="agentConfig.collect_process_info">
            <el-input 
              v-model="processNameListInput" 
              type="textarea" 
              placeholder="每行一个进程名称，例如：nginx" 
              :rows="3"
            />
          </el-form-item>
          
          <el-form-item label="收集日志信息">
            <el-switch v-model="agentConfig.collect_log_info" />
          </el-form-item>
          
          <el-form-item label="收集数据库信息">
            <el-switch v-model="agentConfig.collect_database_info" />
          </el-form-item>
          
          <el-form-item label="日志文件路径">
            <el-input 
              v-model="logPathsInput" 
              type="textarea" 
              placeholder="每行一个路径，例如：/var/log/app.log" 
              :rows="3"
            />
          </el-form-item>
          
          <el-form-item label="监控端口">
            <el-input 
              v-model="portListInput" 
              placeholder="用逗号分隔，例如：80,443,3306" 
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="configDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveAgentConfig">保存配置</el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 批量导入对话框 -->
      <el-dialog v-model="importDialogVisible" title="批量导入服务器" width="500px">
        <el-form label-width="100px">
          <el-form-item label="Excel文件">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
              accept=".xlsx,.xls"
              drag
            >
              <el-icon class="el-icon--upload">
                <UploadFilled />
              </el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  请上传.xls或.xlsx格式的Excel文件
                  <div style="margin-top: 8px;">
                    <el-link type="primary" href="/server_template.xlsx" target="_blank">下载Excel模板</el-link>
                  </div>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="importDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="importServers" :disabled="!importFile">导入</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadInstance, UploadFile, UploadRawFile } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import Layout from '../components/Layout.vue'
import Pagination from '../components/Pagination.vue'
import * as XLSX from 'xlsx'
import { machineAPI } from '../services/api'
import type { Machine, ApiResponse, AgentConfig } from '../types'

// 服务器列表数据
const serverList = ref<Machine[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const totalItems = computed(() => serverList.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

// 分页后的数据
const paginatedServerList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return serverList.value.slice(start, end)
})

// 对话框相关
const dialogVisible = ref(false)
const configDialogVisible = ref(false)
const dialogTitle = ref('新增服务器')
const isEdit = ref(false)
const importDialogVisible = ref(false)
const importFile = ref<UploadRawFile | null>(null)
const uploadRef = ref<UploadInstance>()

// 当前编辑的服务器
const currentServer = reactive({
  id: 0,
  name: '',
  ip: '',
  os: '',
  owner: '',
  port: 22,
  status: 'online' as const,
  createTime: '',
  description: ''
})

// Agent配置
const agentConfig = reactive<AgentConfig>({
  machine_id: 0,
  interval: 30,
  collect_system_info: true,
  collect_cpu_info: true,
  collect_memory_info: true,
  collect_disk_info: true,
  collect_network_info: true,
  collect_process_info: false,
  collect_log_info: false,
  collect_database_info: false,
  log_paths: [],
  database_configs: [],
  port_list: []
})

// 日志路径和端口列表的输入字符串
const logPathsInput = ref('')
const portListInput = ref('')
const processNameListInput = ref('')

// 表单引用
const formRef = ref<FormInstance>()

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入服务器名称', trigger: 'blur' }
  ],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: '请输入正确的IP地址格式', trigger: 'blur' }
  ],
  port: [
    { type: 'number', min: 1, max: 65535, message: '端口号应在1-65535之间', trigger: 'blur' }
  ]
}

// 分页处理函数
const handlePageChange = (page: number) => {
  currentPage.value = page
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
}

// 获取服务器列表
const fetchServerList = async () => {
  try {
    const response = await machineAPI.getAll(0, 100) as ApiResponse<Machine[]>
    if (response.success) {
      serverList.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取服务器列表失败')
    }
  } catch (error: any) {
    console.error('获取服务器列表失败:', error)
    ElMessage.error('获取服务器列表失败: ' + (error.message || '未知错误'))
  }
}

// 打开新增对话框
const openAddDialog = () => {
  console.log('点击了新增服务器按钮')
  dialogTitle.value = '新增服务器'
  isEdit.value = false
  // 重置表单
  Object.assign(currentServer, {
    id: 0,
    name: '',
    ip: '',
    os: '',
    owner: '',
    port: 22,
    status: 'online',
    createTime: '',
    description: ''
  })
  dialogVisible.value = true
  console.log('对话框状态:', dialogVisible.value)
}

// 打开导入对话框
const openImportDialog = () => {
  importDialogVisible.value = true
  importFile.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 处理文件选择
const handleFileChange = (uploadFile: UploadFile) => {
  importFile.value = uploadFile.raw || null
}

// 导入服务器列表
const importServers = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的Excel文件')
    return
  }

  try {
    const data = await importFile.value.arrayBuffer()
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
    
    // 解析数据
    if (jsonData.length <= 1) {
      ElMessage.warning('Excel文件中没有数据')
      return
    }
    
    // 移除标题行
    const headers = jsonData[0] as string[]
    const rows = jsonData.slice(1) as any[][]
    
    // 验证列标题
    const requiredHeaders = ['服务器名称', 'IP地址']
    const missingHeaders = requiredHeaders.filter(header => !headers.includes(header))
    
    if (missingHeaders.length > 0) {
      ElMessage.error(`缺少必需的列: ${missingHeaders.join(', ')}`)
      return
    }
    
    // 解析服务器数据
    const newServers = rows.map((row, index) => {
      const serverData: any = {}
      headers.forEach((header, headerIndex) => {
        serverData[header] = row[headerIndex]
      })
      
      return {
        id: serverList.value.length + index + 1,
        name: serverData['服务器名称'] || '',
        ip: serverData['IP地址'] || '',
        os: serverData['操作系统'] || '',
        owner: serverData['负责人'] || '',
        port: serverData['端口'] ? parseInt(serverData['端口']) : undefined,
        status: 'online' as const,
        createTime: new Date().toLocaleString('zh-CN'),
        description: serverData['描述'] || ''
      }
    }).filter(server => server.name && server.ip) // 过滤掉名称和IP为空的记录
    
    if (newServers.length === 0) {
      ElMessage.warning('没有有效的服务器数据可以导入')
      return
    }
    
    // 添加到服务器列表
    for (const server of newServers) {
      try {
        const response = await machineAPI.create({
          name: server.name,
          ip: server.ip,
          os: server.os,
          owner: server.owner,
          purpose: server.description,
          location: ''
        } as Partial<Machine>) as ApiResponse<Machine>
        
        if (!response.success) {
          ElMessage.error(`创建服务器 ${server.name} 失败: ${response.message}`)
        }
      } catch (error: any) {
        ElMessage.error(`创建服务器 ${server.name} 失败: ${error.message || '未知错误'}`)
      }
    }
    
    ElMessage.success(`成功导入 ${newServers.length} 台服务器`)
    
    // 关闭对话框
    importDialogVisible.value = false
    
    // 重新获取服务器列表
    await fetchServerList()
  } catch (error: any) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败: ' + (error.message || '未知错误'))
  }
}

// 编辑服务器
const editServer = (server: Machine) => {
  dialogTitle.value = '编辑服务器'
  isEdit.value = true
  Object.assign(currentServer, server)
  dialogVisible.value = true
}

// 配置服务器监控
const configServer = async (server: Machine) => {
  try {
    // 获取服务器的Agent配置
    const response = await machineAPI.getAgentConfig(server.id) as ApiResponse<AgentConfig>
    if (response.success && response.data) {
      Object.assign(agentConfig, response.data)
      // 设置日志路径和端口列表的输入字符串
      logPathsInput.value = agentConfig.log_paths.join('\n')
      portListInput.value = agentConfig.port_list.join(',')
      // 设置进程名称列表的输入字符串（如果存在）
      if (agentConfig.process_names) {
        processNameListInput.value = agentConfig.process_names.join('\n')
      }
    } else {
      // 如果没有配置，使用默认配置
      Object.assign(agentConfig, {
        machine_id: server.id,
        interval: 30,
        collect_system_info: true,
        collect_cpu_info: true,
        collect_memory_info: true,
        collect_disk_info: true,
        collect_network_info: true,
        collect_process_info: false,
        collect_log_info: false,
        collect_database_info: false,
        log_paths: [],
        database_configs: [],
        port_list: [],
        process_names: []  // 添加process_names字段
      })
      logPathsInput.value = ''
      portListInput.value = ''
      processNameListInput.value = ''
    }
    
    // 显示配置对话框
    configDialogVisible.value = true
  } catch (error: any) {
    console.error('获取Agent配置失败:', error)
    ElMessage.error('获取Agent配置失败: ' + (error.message || '未知错误'))
  }
}

// 保存Agent配置
const saveAgentConfig = async () => {
  try {
    // 处理日志路径和端口列表
    agentConfig.log_paths = logPathsInput.value.split('\n').filter(path => path.trim() !== '')
    agentConfig.port_list = portListInput.value.split(',').map(port => parseInt(port.trim())).filter(port => !isNaN(port))
    
    // 处理进程名称列表
    if (agentConfig.collect_process_info && processNameListInput.value) {
      agentConfig.process_names = processNameListInput.value.split('\n').filter(name => name.trim() !== '')
    }
    
    // 更新Agent配置
    const response = await machineAPI.updateAgentConfig(agentConfig.machine_id, agentConfig) as ApiResponse<void>
    if (response.success) {
      ElMessage.success('配置保存成功')
      configDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '配置保存失败')
    }
  } catch (error: any) {
    console.error('保存Agent配置失败:', error)
    ElMessage.error('保存Agent配置失败: ' + (error.message || '未知错误'))
  }
}

// 更新服务器激活状态
const updateServerActivate = (server: Machine) => {
  const action = server.is_activate? '禁用' : '激活';
  ElMessageBox.confirm(
    `确定要${action}服务器 "${server.name}" 吗？`,
    `确认${action}`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await machineAPI.updateActivate(server.id, !server.is_activate) as ApiResponse<void>
      if (response.success) {
        ElMessage.success(`${action}成功`)
        // 重新获取服务器列表
        await fetchServerList()
      } else {
        ElMessage.error(response.message || `${action}失败`)
      }
    } catch (error: any) {
      console.error(`${action}失败:`, error)
      ElMessage.error(`${action}失败: ` + (error.message || '未知错误'))
    }
  }).catch(() => {
    ElMessage.info(`已取消${action}`)
  })
}

// 保存服务器
const saveServer = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response: ApiResponse<Machine>
        if (isEdit.value) {
          // 编辑模式
          response = await machineAPI.update(currentServer.id, {
            name: currentServer.name,
            ip: currentServer.ip,
            os: currentServer.os,
            owner: currentServer.owner,
            purpose: currentServer.description,
            location: ''
          } as Partial<Machine>) as ApiResponse<Machine>
        } else {
          // 新增模式
          response = await machineAPI.create({
            name: currentServer.name,
            ip: currentServer.ip,
            os: currentServer.os,
            owner: currentServer.owner,
            purpose: currentServer.description,
            location: ''
          } as Partial<Machine>) as ApiResponse<Machine>
        }
        
        if (response.success) {
          ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          // 重新获取服务器列表
          await fetchServerList()
        } else {
          ElMessage.error(response.message || (isEdit.value ? '编辑失败' : '新增失败'))
        }
      } catch (error: any) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      }
    }
  })
}

// 组件挂载时的初始化操作
onMounted(async () => {
  console.log('监控配置页面已加载')
  await fetchServerList()
})
</script>

<style scoped>
.monitor-config-page {
  padding: 20px;
}

.config-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 10;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

</style>